package com.hitqz.robot.biz.flow.component.agv;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.api.common.entity.RobotMapPos;
import com.hitqz.robot.biz.business.dispatch.DispatchService;
import com.hitqz.robot.biz.flow.config.FlowInterruptException;
import com.hitqz.robot.biz.flow.domain.constant.FlowConstant;
import com.hitqz.robot.biz.flow.util.LiteFlowUtil;
import com.hitqz.robot.biz.service.RobotMapPosService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.driver.model.IRobotPosDto;
import com.hitqz.robot.driver.parent.RobotDriverService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author xupkun
 * @date 2025/2/5
 */

@Slf4j
@LiteflowComponent(value = "AgvPutPoint", name = "[轮对/轮轴]AGV固定点放置")
@RequiredArgsConstructor
public class AgvPutPoint extends NodeComponent {

    private final RobotMapPosService robotMapPosService;

    private final RobotService robotService;

    private final DispatchService dispatchService;

    private final RobotDriverService robotDriverService;

    @Override
    public void process() throws Exception {
        String key = FlowConstant.NODE_CUSTOM_INFO_MAP.get(this.getNodeId()).getParamNames().get(0);
        String posCode = this.getCmpData(JSONObject.class).get(key, String.class);
        log.info("放置的位置是:" + posCode);
        Robot robot = robotService.getDefaultRobot();
        RobotMapPos robotMapPos = robotMapPosService.
                getOne(Wrappers.<RobotMapPos>lambdaQuery().eq(RobotMapPos::getCode, posCode)
                        .eq(RobotMapPos::getMapCode, robot.getMapCode())
                        .last("limit 1"));

        if (robotMapPos == null) {
            log.info("找不到相关的点位");
            LiteFlowUtil.setInterruptFlag();
            LiteFlowUtil.checkInterruptFlag();
            return ;
        }

        boolean isSuccess = dispatchService.go2TargetPosition(robotMapPos, false);

        TimeUnit.SECONDS.sleep(3);
        IRobotPosDto iRobotPosDto = robotDriverService.getWebPos();
        while (true) {
            try {
                iRobotPosDto = robotDriverService.getWebPos();
                if (iRobotPosDto != null &&
                        iRobotPosDto.getCurrentStation() != null &&
                        iRobotPosDto.getCurrentStation().equals(robotMapPos.getCode()) && iRobotPosDto.isReached()) {
                    log.info("机器人到达位置");
                    break;
                }
                LiteFlowUtil.checkInterruptFlag();
                TimeUnit.SECONDS.sleep(1);
            } catch (FlowInterruptException e) {
                break;
            } catch (NullPointerException e) {

            }

        }


    }
}
